package com.example.service.impl;

import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.pojo.Dept;
import com.example.pojo.DeptLog;
import com.example.service.DeptLogService;
import com.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        List<Dept> list = deptMapper.list();
        return list;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) throws Exception {
        try {
            //删除部门的所有员工
            empMapper.deleteByDeptId(id);
            int i = 1/0;
//            if (true)
//            {
//                throw new Exception("出错");
//            }
            //根据id删除部门
            deptMapper.delete(id);
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此次解散的是"+id+"号部门");
            deptLogService.insert(deptLog);
        }


    }

    @Override
    public void addDept(Dept dept) {
          dept.setCreateTime(LocalDateTime.now());
          dept.setUpdateTime(LocalDateTime.now());
        System.out.println(dept);
          deptMapper.insert(dept);
    }

    @Override
    public Dept selectById(Integer id) {
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    public void update(Dept dept)
    {
        deptMapper.update(dept);
    }
}
